<?php

namespace app\service;

use app\modules\Admin\models\storememberModel;
use Illuminate\Database\Capsule\Manager as DB;
use \app\service\member as memberService;

class auth
{
    public static function register($nickname, $password, $inviter = null, $extend = [])
    {
        $salt   = randStr(6);
        $member = new \memberModel();
        $member->nickname = $nickname;
        $member->salt     = $salt;
        $member->password = $password ?  md5($password . $salt) : '';
        $member->avatar = $extend['avatar'] ?? 'http://img.zy52.cn/164552512181362224742.png';
        $member->phone = $extend['phone'] ?? '';
        $member->email = $extend['email'] ?? '';
        $member->token = md5($salt . $password . $extend['phone'] . $nickname . time() . rand(10000, 99999));
        $member->level = 1;
        $member->score = 0;
        $member->money = 0;
        $member->join_time = timestamp();
        $member->parent_member_id = $inviter->id ?? 0;
        $member->save();

        //注册成功的事件
        if ($inviter) {
            \Hook::emit('user_register_successed', ['member' => $member, 'inviter' => $inviter]);
        }

        return $member;
    }

    public static function checkWeakPassword($password)
    {
        return (ctype_digit($password) || preg_match("/^[a-zA-Z\s]+$/", $password));
    }

    public static function login($member)
    {
        $ip = getIp();
        $token = $member->token
            ? $member->token
            : md5($member->id . $ip . $member->phone . $member->nickname . $member->logined_at . rand(10000, 99999));
        $member->token = $token;
        $member->try_times = 0;
        $member->login_times += 1;
        $member->logined_ip = $ip;
        $member->logined_at = date('Y-m-d H:i:s');
        $member->save();
        return [
            'token' => $token,
            'mobile' => $member->phone,
            'nickname' => $member->nickname,
            'avatar' => $member->avatar,
        ];
    }

    public static function checklogin($abort = false)
    {
        $token = getHeader('token');
        if ($token === '' && $abort) {
            json(['code' => 401, 'msg' => '请登录']);
            exit;
        }
        $member = \memberModel::where('token', $token)->first();
        if (!$member && $abort) {
            json(['code' => 401, 'msg' => '登录状态已失效']);
            exit;
        }
        return $member;
    }

    public static function getUser()
    {
        return self::checklogin();
    }

    public static function userinfo($member = null)
    {
        $member = $member ?: self::getUser();
        if ($member) {
            $allow_fields = [
                'id', 'username', 'nickname', 'realname', 'idcardno', 'signmobile',
                'sign_address', 'remark', 'phone', 'avatar', 'score', 'score_old',
                'birthday', 'money', 'money_old', 'group', 'group_id', 'verification',
                'child_user_count', 'total_consume', 'team_order_count', 'team_consume',
                'team_income', 'pay_pwd', 'parent_member_id', 'signstatus', 'pay_password',
                'jindou', 'quanyi', 'hongbao'
            ];
            $info = $member->toArray();
            $userinfo = array_intersect_key($info, array_flip($allow_fields));
            $userinfo['avatar'] = cdnurl($info['avatar']);
            $userinfo['mobile'] = $info['phone'];
            $userinfo['parent_user_id'] = $info['parent_member_id'];
            $oauth = \memberoauthModel::where('member_id', $member->id)->where('platform', 'wxOfficialAccount')->first();
            $userinfo['verification'] = [
                'email' => (int) (!empty($member->email)),
                'mobile' => (int) (!empty($member->phone)),
                'wxOfficialAccount' => (int) (!empty($oauth)),
            ];
            $userinfo['pay_pwd'] = $info['pay_password'];
            $userinfo['daoshi'] = [];
            $count = \memberchildrenModel::where('member_id', $member->id)->count();
            $userinfo['count'] = ['total' => $count];

            $delay_money = array_sum([
                \agentrewardModel::where('agent_id', $member->id)->where('status', 0)->sum('commission'),
                \gudongrewardModel::where('gudong_id', $member->id)->where('status', 0)->sum('commission'),
                \tuikerewardModel::where('tuike_id', $member->id)->where('status', 0)->sum('commission'),
                \qudairewardModel::where('qudai_id', $member->id)->where('status', 0)->sum('commission'),
                \dianpurewardModel::where('manager_id', $member->id)->where('status', 0)->sum('commission'),
                \twostagerewardModel::where('twostage_id', $member->id)->where('status', 0)->sum('commission'),
            ]);
            $agent_level = \agentlevelModel::find($member->level);
            $userinfo['agent'] = [
                'level' => $agent_level,
                'delay_money' => bcadd($delay_money ?: 0, '0', 2),
                'total_income' => bcadd($member->total_income ?: 0, '0', 2),
            ];

            $userinfo['team_total'] = \memberchildrenModel::where('member_id', $member->id)->count();

            $userinfo['child_user_count'] = $userinfo['team_total'];
            $userinfo['child_user_count_1'] = \memberchildrenModel::where('member_id', $member->id)
                ->where('level', 1)
                ->count();
            $userinfo['child_user_count_2'] = \memberchildrenModel::where('member_id', $member->id)
                ->where('level', 2)
                ->count();

            $userinfo['pickgoodscard'] = DB::table('member_pickgoods_card')
                ->where('member_id', $member->id)
                ->where(function ($query) {
                    $query->whereNull('expire')->orWhere('expire', '>', date('Y-m-d H:i:s'));
                })
                ->count();
        }
        return $userinfo ?? [];
    }

    public static function userdata($member = null)
    {
        $member = $member ?: self::getUser();
        $all = \memberchildrenModel::where('member_id', $member->id)->whereHas('child')->count();
        $direct = \memberchildrenModel::where('member_id', $member->id)->where('level', 1)->whereHas('child')->count();
        $other = $all - $direct;
        $data['teamcount'] = ['all' => $all, 'direct' => $direct, 'other' => $other];

        $data['id'] = $member->id;
        $data['avatar'] = $member->avatar;
        $data['nickname'] = $member->nickname;
        $data['mobile'] = $member->phone;
        $data['coupons_num'] = 0;
        $data['coupons_num'] = 0;
        $data['is_store'] = 0;
        $data['store_id'] = 0;
        $data['dianpu_id'] = 0;
        $data['is_qudai'] = 0;
        $data['qudai_level'] = 0;
        $data['qudai_name'] = '';

        $parent_user_info = \memberModel::find($member->parent_member_id);
        if (!empty($parent_user_info)) {
            $data['parent_user_info'] = [
                'id' => $parent_user_info->id,
                'avatar' => $parent_user_info->avatar,
                'nickname' => $parent_user_info->nickname,
                'mobile' => $parent_user_info->phone,
            ];
        }

        $data['order_num'] = [
            'aftersale' => \orderModel::where('member_id', $member->id)
                ->where('status', \orderModel::STATUS_PAYED)
                ->whereHas('item', function ($query) {
                    $query->where('aftersale_status', \orderitemModel::AFTERSALE_STATUS_AFTERING);
                })
                ->count(),
            'nocomment' => \orderModel::where('member_id', $member->id)
                ->where('status', \orderModel::STATUS_PAYED)
                ->whereHas('item', function ($query) {
                    $query
                        ->where('dispatch_status', \orderitemModel::DISPATCH_STATUS_GETED)
                        ->where('comment_status', \orderitemModel::COMMENT_STATUS_NO);
                })
                ->count(),
            'noget' => \orderModel::where('member_id', $member->id)
                ->where('status', \orderModel::STATUS_PAYED)
                ->whereHas('item', function ($query) {
                    $query
                        ->where('dispatch_status', \orderitemModel::DISPATCH_STATUS_SENDED)
                        ->where('refund_status', 0);
                })
                ->count(),
            'nopay' => \orderModel::where('member_id', $member->id)
                ->where('status', \orderModel::STATUS_NOPAY)
                ->count(),
            'nosend' => \orderModel::where('member_id', $member->id)
                ->where('status', \orderModel::STATUS_PAYED)
                ->whereHas('item', function ($query) {
                    $query->where('dispatch_status', \orderitemModel::DISPATCH_STATUS_NOSEND)
                        ->where('refund_status', 0)
                        ->where('aftersale_status', 0);
                })
                ->count(),
        ];

        // 查询用户是否是门店管理员
        $userStores = storememberModel::where('member_id', $member->id)->get();
        $data['is_store'] = 0;
        foreach ($userStores as $k => $store) {
            $data['is_store'] = 1;
            $data['store_id'] = $store->store_id;
            if ($k > 0) {
                $data['store_id'] = 0;
            }
        }
        $dianpu = \dianpuModel::query()->where('member_id', $member->id)->where('status', 1)->first();
        if($dianpu){
            $data['dianpu_id'] = $dianpu->id;
        }
        $qudai = \qudaiModel::query()->with('qudai_level')->where('qudai_id', $member->id)->first();
        if ($qudai){
            $data['is_qudai'] = 1;
            if($qudai->qudai_level){
                $data['qudai_level'] = $qudai->qudai_level->level;
                $data['qudai_name'] = $qudai->qudai_level->name;
            }
        }
        return $data;
    }

    public static function thirdoauthinfo()
    {
        $member = self::getUser();
        if ($member) {
            // TODO 查询用户三方授权信息
            $data = [];
        }
        return $data ?? null;
    }

    public static function bindParentUser($inviterId)
    {
        $userinfo = self::userinfo();
        // 查询上级用户
        $parent_user = \memberModel::where('id', $inviterId)->orWhere('phone', $inviterId)->first();
        if (empty($parent_user)) {
            throw new \Exception('上级用户不存在');
        }
        // 不可绑定自己
        if ($parent_user->id == $userinfo['id']) {
            throw new \Exception('不可绑定自己');
        }
        // 不可绑定自己的下级
        if (\memberchildrenModel::where('member_id', $userinfo['id'])->where('children_id', $inviterId)->exists()) {
            throw new \Exception('不能将自己的下线设置为推荐人');
        }
        memberService::changeParent($userinfo['id'], $parent_user->id, 'user', $userinfo['id'], '会员操作绑定推荐人');
        return true;
    }

    public static function bindMobileParent($params)
    {
        $userinfo = self::userinfo();
        // 查询推荐人
        if( $params['inviterId'] && $params['inviterId']>0 ) {
            $parent_user = \memberModel::where('id', $params['inviterId'])->orWhere('phone', $params['inviterId'])->first();
            if (empty($parent_user)) {
                throw new \Exception('上级用户不存在');
            }
            // 不可绑定自己
            if ($parent_user->id == $userinfo['id']) {
                throw new \Exception('不可绑定自己');
            }
            // 不可绑定自己的下级
            if (\memberchildrenModel::where('member_id', $userinfo['id'])->where('children_id', $params['inviterId'])->exists()) {
                throw new \Exception('不能将自己的下线设置为推荐人');
            }
        }

        DB::transaction(function () use ($params, $userinfo, $parent_user){
            if (\memberModel::where('phone', $params['mobile'])->exists()) {
                $target_id = \memberModel::where('phone', $params['mobile'])->value('id');

                // 合并账号
                if($target_id!==$userinfo['id']) {
                    memberService::merge($userinfo['id'], $target_id, 'user', $userinfo['id'], '前台会员操作合并账号');
                }
            }else{
                $rows = ['phone' => $params['mobile']];
                if($params['inviterId'] && $params['inviterId']>0) {
                    // $rows['parent_member_id'] = $params['inviterId'];
                    memberService::changeParent($userinfo['id'], $parent_user->id, 'user', $userinfo['id'], '会员操作绑定推荐人');
                }
                \memberModel::where('id', $userinfo['id'])->update($rows);
            }
        });
        return true;
    }

    public static function setOper($operType = '', $operId = 0)
    {
        if ($operType === '') {
            // 自动获取操作人
            $adminauth = new \Auth(_RBACCookieKey_);
            if ($adminauth->isLogin()) {
                // 后台管理员
                $operType = 'admin';
                $operId = $adminauth->user_id;
            } else {
                $user = self::getUser();
                if ($user) {
                    $operType = 'user';
                    $operId = $user->id;
                }
            }
            // else if (strpos(request()->url(), 'store.store') !== false) {
            //     // 门店
            //     $store = Store::info();
            //     if ($store) {
            //         $operType = 'store';
            //         $operId = $store['id'];
            //     }
            // } else if (strpos(request()->url(), 'addons/shopro') !== false) {
            //     // 用户
            //     $user = User::info();
            //     if ($user) {
            //         $operType = 'user';
            //         $operId = $user->id;
            //     }
            // }
        }
        if ($operType === '') {
            $operType = 'system';
        }
        return [
            'oper_type' => $operType,
            'oper_id' => $operId
        ];
    }

    public static function getOper($operType, $operId)
    {
        $operator = null;
        if ($operType === 'admin') {
            $operator = \adminModel::select('nickname as name, avatar')->find($operId);
            $operator['type'] = '管理员';
        } elseif ($operType === 'user') {
            $operator = \memberModel::select('nickname as name, avatar')->find($operId);
            $operator['type'] = '用户';
        }
        // elseif ($operType === 'store') {
        //     $operator = \storeModel::select('name')->find($operId);
        //     $operator['type'] = '用户';
        //     $operator['avatar'] = '';
        // }
        else {
            $operator = [
                'name' => '系统',
                'avatar' => '',
                'type' => '系统'
            ];
        }
        if(!isset($operator['name'])) {
            $operator['name'] = '已删除';
            $operator['avatar'] = '';
        }
        return $operator;
    }

    public static function logout()
    {
        $allheaders = getallheaders();
        $token = $allheaders['Token'] ?? '';
        if ($token !== '') {
            $member = self::getUser();
            \memberModel::where('token', $token)->update(['token' => md5($member->salt . $member->password . $member->phone . $member->nickname . time() . rand(10000, 99999))]);
        }
    }
}

